package com.yg.config.interceptor;

import com.yg.config.result.R;
import com.yg.config.result.ResultCode;
import com.yg.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * @author: 备备
 * @Date:2020/11/7
 * @Description:com.yg.config 全局拦截器实现类
 * @Version:1.0
 */
@Slf4j
public class GlobalInterceptor implements HandlerInterceptor {

    private boolean b;

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //允许跨域请求
        {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
            response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type,Token,Accept, Connection, User-Agent, Cookie");
            response.setHeader("Access-Control-Max-Age", "3628800");
        }
        //设置返回参数
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");

        log.info("执行了 GlobalInterceptor 的preHandle方法");
        //定义token验证后的状态
        String token = request.getHeader("token");

        if (null == token) {
            log.info("token为空！！！");
            response.getWriter().write(R.ERROR().code(ResultCode.TOKENERROR).message("token为空！").toString());
            b = false;
        } else {
            log.info("用户提交的token:" + token);
            String method = request.getMethod();
            switch (method) {
                case "GET":
                    b = JwtUtils.checkToken(token);
                    break;
                case "POST":
                    b = JwtUtils.checkToken(request);
                    break;
                case "DELETE":
                    b = JwtUtils.checkToken(token);
                    break;
                case "PUT":
                    b = JwtUtils.checkToken(token);
                    break;
                default:
                    b = JwtUtils.checkToken(token);
                    break;
            }
            log.info("身份验证：" + b);
            if (!b){
                response.getWriter().write(R.ERROR().code(ResultCode.TOKENISNULL).message("token验证失败！").toString());
            }
        }

//      如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
        return b;
        //如果设置为true时，请求将会继续执行后面的操作
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
}
